package com.mlamp.广度优先遍历算法;

import com.alibaba.fastjson.JSONObject;

import java.util.*;

public class 从上到下打印二叉树III {

    public static void main(String[] args) {
        从上到下打印二叉树III instance = new 从上到下打印二叉树III();

        TreeNode root = new TreeNode(3);
        TreeNode left = new TreeNode(9);
        TreeNode right = new TreeNode(20, new TreeNode(15), new TreeNode(7));
        root.left = left;
        root.right = right;
        List<List<Integer>> lists = instance.levelOrder(root);
        System.out.println(JSONObject.toJSONString(lists));

        lists = instance.levelTraversal(root);
        System.out.println(JSONObject.toJSONString(lists));
    }

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int x) {
            this.val = x;
        }

        public TreeNode(int x, TreeNode left, TreeNode right) {
            this.val = x;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> levelTraversal(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        boolean reverse = false;
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> midRes = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left != null) queue.offer(poll.left);
                if (poll.right != null) queue.offer(poll.right);
                if (reverse) {
                    midRes.add(poll.val);
                } else {
                    midRes.add(0, poll.val);
                }
            }
            result.add(midRes);
            reverse = !reverse;
        }
        return result;
    }


    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        boolean reverse = true;
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> set = new ArrayList<>();
            for (int index = 0; index < size; index++) {
                TreeNode poll = queue.poll();
                if (reverse) {
                    set.add(poll.val);
                } else {
                    set.add(0, poll.val);
                }
                if (poll.left != null) queue.add(poll.left);
                if (poll.right != null) queue.add(poll.right);
            }
            reverse = !reverse;
            result.add(set);
        }
        return result;
    }
}
